<?php

namespace app\yperp\logic\yp;

use app\yperp\model\YpOrderGoods;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use think\Db;
use app\yperp\model\YpOrderGoods as ModelYpOrderGoods;


class YpExpress
{
    private static $instance;
    protected  $token;
    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    } 

    function token(){
        return YpLogin::getInstance()->login('csmb', 'hcyp1234!');
    }

    protected  function Request($method = 'POST', $url, $body)
    {
        $client = new Client([
            'verify' => env('root_path') . 'application\yperp\common\cacert.pem',
            // 忽略证书验证
        ]);
        $headers = [
            'Content-Type' => 'application/json;charset=UTF-8',
            'token' => $this->token(),
        ];
        // $body = '{"page": 1,"limit": 10,"startTime": "2024-02-17","endTime": "2024-03-19"}';
        $body = json_encode($body, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        $request = new Request($method, $url, $headers, $body);
        $response = $client->sendAsync($request)->wait();
        $data = $response->getBody()->getContents();
        // dump($data);
        $data = json_decode($data, true);
        return $data;
    }
   

    /**
     * 获取快递公司列表
     */
    function queryExpressList()
    {

        $url = 'https://yp.changhong.com/platform-frame-web-admin/api/sysExpress/queryExpressList';
        $datas = $this->Request('POST', $url, ['status' => 1]);

        $datas = $datas['body'];

        foreach ($datas as $item) {
            // dump($item);
            Db::startTrans();
            try {
                $where = ['id' => $item['id']];
                $data = Db::name('yperp_express')->where($where)->find();
                if ($data) {
                    Db::name('yperp_express')->where($where)->update($item);
                } else {
                    Db::name('yperp_express')->where($where)->insert($item);
                }
                Db::commit();
            } catch (\Throwable $th) {
                Db::rollback();
                dump($th->getMessage());
                dump($th->getTraceAsString());
                throw $th;
            }
        }
    }


    function getOrderDetailsId($orderCode = '')
    {
        $url = 'https://yp.changhong.com/platform-frame-web-admin/api/orderItem/details';
        $datas = $this->Request('POST', $url, ['orderCode' => $orderCode,]);
        return $datas['body']['id'];
    }

    public function pushexpress($orderCode = '')
    {
        $data_list = ModelYpOrderGoods::withJoin('yporder')->where(['yporder.orderCode' => $orderCode])->find();

        dump([$data_list['expr_corp'], $data_list['expr_code']]);

        $res =    $this->sendGoods([
            'expr_corp' => $data_list['expr_corp'],
            'expr_code' => $data_list['expr_code'],
            'orderCode' => $orderCode,
            'sendGoodsNum' => $data_list['buyNum'],
        ]);
        if ($res) {
            // $goods = ModelYpOrderGoods::where(['orderCode' => $orderCode])->update(['status' => 4]);
        }
    }


    function sendGoods($params = [])
    {
        $datas = [];
        $url = 'https://yp.changhong.com/platform-frame-web-admin/api/orderItem/sendGoods';
        $Expr = Db::name('yperp_express')->whereLike('companyName', '%' . $params['expr_corp'] . '%')->find();
        // dump($Expr);
        // dump(Db::getLastSql());
        if ($Expr) {
            $goods = YpOrderGoods::where(['orderCode' => $params['orderCode']])->field('goodsId,goodsName,goodsPic')->find()->toArray();
            $goods['sendGoodsNum'] =  $params['sendGoodsNum'];
            $request_params =   [
                'deliveryCompanyCode' => $Expr['companyCode'],
                'deliveryCompanyName' => $Expr['companyName'],
                'deliverySn' => $params['expr_code'], // 运单号 "线下自提",
                'logistics' => "",
                'operationRemark' => "",
                'orderItemId' => $this->getOrderDetailsId($params['orderCode']), //HC2402167088000071
                'orderSendGoodsDtos' => [
                    $goods,
                ],
            ];

            $datas = $this->Request('POST', $url, $request_params);
        } else {
            // dump('没有找到快递公司:' . $params['expr_corp']);
            return false;
        }
        if ($datas['errorCode'] == 0) {
            return true;
        } else {
            return false;
        }
    }
}
